package logic

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"order_srv/internal/model"

	"order_srv/internal/svc"
	"order_srv/order_proto"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderListLogic {
	return &OrderListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderListLogic) OrderList(in *order_proto.OrderListRequest) (*order_proto.OrderListInfo, error) {
	// todo: add your logic here and delete this line
	var orders []model.Order
	if in.Page == 0 {
		in.Page = 1
	}
	if in.Limit == 0 {
		in.Limit = 2
	}
	offset := (in.Page - 1) * in.Limit
	tx := model.DB.Where(&model.Order{UserId: in.UserId}).Offset(int(offset)).Limit(int(in.Limit)).Find(&orders)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "查询订单列表失败")
	}
	var orderList []*order_proto.OrderInfo
	for _, v := range orders {
		orderList = append(orderList, &order_proto.OrderInfo{
			Id:      int32(v.ID),
			UserId:  v.UserId,
			GoodsId: v.GoodsId,
			Price:   v.Price,
			PayType: v.PayType,
			Status:  v.Status,
			OrderSn: v.OrderSn,
			TradeNo: v.TradeNo,
			Num:     v.Num,
		})
	}
	return &order_proto.OrderListInfo{OrderInfo: orderList}, nil
}
